import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../model/notes_continuation.dart';
import '../utils/Adapt.dart';

/// 文章续写展示组件
/// 包含上一集按钮和下一集横向列表
class NotesContinuationWidget extends StatelessWidget {
  final NotesContinuation? continuation;
  final Function(int notesId, int noteType)? onNavigateToNote;
  final Function(int notesId)? onShowStoryTree; // 查看故事树回调
  final int currentNoteType; // 当前文章类型（0=图片，1=视频）
  final int currentNotesId; // 当前文章ID

  const NotesContinuationWidget({
    Key? key,
    this.continuation,
    this.onNavigateToNote,
    this.onShowStoryTree,
    this.currentNoteType = 0,
    required this.currentNotesId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (continuation == null) {
      return const SizedBox.shrink();
    }

    bool hasPrevious = continuation!.previousNotes != null;
    bool hasNext = continuation!.nextNotesList.isNotEmpty;

    if (!hasPrevious && !hasNext) {
      return const SizedBox.shrink();
    }

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey.shade200, width: 1),
          bottom: BorderSide(color: Colors.grey.shade200, width: 1),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 上一集按钮和故事全貌按钮
          if (hasPrevious) _buildPreviousButton(),
          
          // 故事全貌按钮（有上一集或下一集时显示）
          if (hasPrevious || hasNext) 
            Padding(
              padding: const EdgeInsets.only(top: 12),
              child: _buildStoryTreeButton(),
            ),
          
          // 分隔符
          if (hasPrevious && hasNext) const SizedBox(height: 20),
          if (!hasPrevious && hasNext) const SizedBox(height: 12),
          
          // 下一集列表
          if (hasNext) _buildNextList(),
        ],
      ),
    );
  }

  /// 构建上一集按钮
  Widget _buildPreviousButton() {
    final previous = continuation!.previousNotes!;
    
    return InkWell(
      onTap: () => onNavigateToNote?.call(previous.notesId, previous.notesType),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.blue.shade200, width: 1),
        ),
        child: Row(
          children: [
            // 封面图
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: previous.coverPicture,
                width: 80,
                height: 80,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  color: Colors.grey.shade200,
                  child: const Center(
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                ),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey.shade300,
                  child: const Icon(Icons.image_not_supported, 
                    color: Colors.grey, size: 30),
                ),
              ),
            ),
            
            const SizedBox(width: 12),
            
            // 文本信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标签
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8, 
                      vertical: 4,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade700,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: const Text(
                      '⬆️ 上一集',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 8),
                  
                  // 标题
                  Text(
                    previous.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                      height: 1.4,
                    ),
                  ),
                  
                  const SizedBox(height: 6),
                  
                  // 统计信息
                  Row(
                    children: [
                      Icon(Icons.thumb_up_outlined, 
                        size: 14, 
                        color: Colors.grey.shade600,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        _formatCount(previous.notesLikeNum),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Icon(Icons.star_outline, 
                        size: 14, 
                        color: Colors.grey.shade600,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        _formatCount(previous.notesCollectionNum),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 箭头图标
            Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colors.blue.shade700,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建下一集列表
  Widget _buildNextList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题
        Row(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 10, 
                vertical: 6,
              ),
              decoration: BoxDecoration(
                color: Colors.orange.shade700,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(
                '⬇️ 下一集 (${continuation!.nextNotesList.length})',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const Spacer(),
            Text(
              '左右滑动查看更多',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey.shade500,
              ),
            ),
          ],
        ),
        
        const SizedBox(height: 12),
        
        // 横向滚动列表
        SizedBox(
          height: 200,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: continuation!.nextNotesList.length,
            itemBuilder: (context, index) {
              final next = continuation!.nextNotesList[index];
              return _buildNextCard(next, index);
            },
          ),
        ),
      ],
    );
  }

  /// 构建下一集卡片
  Widget _buildNextCard(NextNotesInfo next, int index) {
    // 热度排名颜色
    Color? rankColor;
    if (index == 0) {
      rankColor = Colors.orange.shade700; // 第一名：金色
    } else if (index == 1) {
      rankColor = Colors.grey.shade600; // 第二名：银色
    } else if (index == 2) {
      rankColor = Colors.brown.shade400; // 第三名：铜色
    }

    return InkWell(
      onTap: () => onNavigateToNote?.call(next.notesId, next.notesType),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        width: 160,
        margin: EdgeInsets.only(
          right: 12,
          left: index == 0 ? 0 : 0,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: rankColor ?? Colors.grey.shade300,
            width: rankColor != null ? 2 : 1,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 封面图 + 排名徽章
            Stack(
              children: [
                ClipRRect(
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(11),
                    topRight: Radius.circular(11),
                  ),
                  child: CachedNetworkImage(
                    imageUrl: next.coverPicture,
                    width: double.infinity,
                    height: 120,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      color: Colors.grey.shade200,
                      child: const Center(
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: Colors.grey.shade300,
                      child: const Icon(Icons.image_not_supported, 
                        color: Colors.grey, size: 40),
                    ),
                  ),
                ),
                
                // 排名徽章（前3名）
                if (rankColor != null)
                  Positioned(
                    top: 8,
                    left: 8,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: rankColor,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.3),
                            blurRadius: 4,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            index == 0 
                              ? Icons.emoji_events 
                              : Icons.stars,
                            size: 14,
                            color: Colors.white,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            'NO.${index + 1}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 11,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                
                // 层级标签
                Positioned(
                  top: 8,
                  right: 8,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 6,
                      vertical: 3,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      'L${next.continuationLevel}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            
            // 文本信息
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      next.title,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                        height: 1.3,
                      ),
                    ),
                    
                    const Spacer(),
                    
                    // 统计信息
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.thumb_up,
                              size: 13,
                              color: next.notesLikeNum > 100 
                                ? Colors.orange.shade700 
                                : Colors.grey.shade600,
                            ),
                            const SizedBox(width: 3),
                            Text(
                              _formatCount(next.notesLikeNum),
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: next.notesLikeNum > 100 
                                  ? FontWeight.bold 
                                  : FontWeight.normal,
                                color: next.notesLikeNum > 100 
                                  ? Colors.orange.shade700 
                                  : Colors.grey.shade600,
                              ),
                            ),
                          ],
                        ),
                        
                        // 热度指示
                        if (next.notesLikeNum > 100)
                          Icon(
                            Icons.local_fire_department,
                            size: 16,
                            color: Colors.orange.shade700,
                          ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建故事全貌按钮
  Widget _buildStoryTreeButton() {
    return InkWell(
      onTap: () => onShowStoryTree?.call(currentNotesId),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Colors.purple.shade400,
              Colors.deepPurple.shade500,
            ],
          ),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.purple.withOpacity(0.3),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.account_tree,
              color: Colors.white,
              size: 24,
            ),
            const SizedBox(width: 12),
            const Text(
              '查看故事全貌',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
                letterSpacing: 0.5,
              ),
            ),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.3),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Text(
                '鱼骨图',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化数字（K、W）
  String _formatCount(int count) {
    if (count >= 10000) {
      return '${(count / 10000).toStringAsFixed(1)}w';
    } else if (count >= 1000) {
      return '${(count / 1000).toStringAsFixed(1)}k';
    } else {
      return count.toString();
    }
  }
}

